import {defaultErrorHandler, errorHandler} from "./requestErrorHandle"
import store from "../store"

const baseURL = "http://192.168.2.6:1337/";

function request(options = {}) {
    if (store.getters["user/hasLogin"]) {
        if (!options.header) options.header = {};
        options.header.Authorization = `Bearer ${store.getters["user/getAccessToken"]}`
    }
    return new Promise((resolve, reject) => {
        uni.request({
            ...options,
            url: baseURL + (options.url ?? ''),
            method: options.method || 'GET',
            data: options.data || {},
            success: (res) => {
                console.log("request", options, "success", res)
                if (res.statusCode !== 200 || res.data.errMsg){
                    errorHandler(res)
                    reject(res)
                }

                if (res.data.msg){
                    uni.showToast({
                        icon: 'none',
                        title: res.data.msg,
                        duration: 3000
                    });
                }

                resolve(res.data)
            },
            fail: (err) => {
                console.log("request", options, "fail", err)
                errorHandler(err)
                reject(err)
            },
            complete: () => {
            }
        })
    })
}

['get', 'post', 'put', 'delete', 'patch'].forEach((method) => {
    request[method] = (url, data, options) => {
        return request({
            ...options,
            url,
            data,
            method,
        })
    }
})

export default request
